<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.keywords" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordsSearch">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="batchEmpDelete">批量删除删除</el-button>
        </el-form-item>

      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="employeeInfo.rows" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">


      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="商品名称">
              <span>{{ props.row.username }}</span>
            </el-form-item>
            <el-form-item label="员工密码">
              <span>{{ props.row.password }}</span>
            </el-form-item>
            <el-form-item label="员工 ID">
              <span>{{ props.row.id }}</span>
            </el-form-item>

            <el-form-item label="部门名称">
              <span>{{ props.row.department.name }}</span>
            </el-form-item>
            <el-form-item label="部门层级">
              <span>{{ props.row.department.path }}</span>
            </el-form-item>
            <el-form-item label="员工邮件">
              <span>{{ props.row.email }}</span>
            </el-form-item>
            <el-form-item label="员工头像">
              <span>{{ props.row.headImage }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="username" label="姓名" width="160" sortable>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="100">
      </el-table-column>
      <el-table-column prop="department.name" label="部门名称" width="160" sortable>
      </el-table-column>
      <el-table-column prop="department.path" label="部门层级" min-width="80" sortable>
      </el-table-column>
      <el-table-column prop="password" label="员工密码" min-width="80" sortable>
      </el-table-column>
      <el-table-column prop="email" label="邮件" min-width="180" sortable>
      </el-table-column>
      <el-table-column prop="phone" label="电话" min-width="180" sortable>
      </el-table-column>
      <el-table-column prop="logininfoId" label="loginInfo" min-width="180" sortable>
      </el-table-column>
      <el-table-column  label="员工id" min-width="180" sortable>
                <template scope="scope">
                  <span >{{scope.row.id}}&nbsp;</span>

                </template>
      </el-table-column>

      <el-table-column prop="headImage" label="头像" min-width="180" sortable>

        <template>

          <img src="headImage" style="width: 50px;height: 50px">
        </template>
      </el-table-column>
      <el-table-column label="操作" width="400">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="warning" size="small" @click="handleRole(scope.$index, scope.row)">设置角色</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="query.pageSize"
        :current-page="query.currentPage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="employeeInfo.total">
    </el-pagination>


    <!--新增界面-->
    <el-dialog title="新增/修改" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">

        <el-form-item label="员工名字" label-width="60" prop="username">
          <el-input v-model="addForm.username" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="修改员工密码" label-width="60" prop="password">
          <el-input v-model="addForm.password" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="所属部门" label-width="60">

          <el-cascader v-model="addForm.department"
                       :options="deptTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}" clearable>
          </el-cascader>
        </el-form-item>

        <el-form-item label="年龄">
          <el-input-number v-model="addForm.age" :min="0" :max="200"></el-input-number>
        </el-form-item>

        <el-form-item label="邮件" label-width="160">
          <el-input v-model="addForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" label-width="160">
          <el-input v-model="addForm.phone" type="number" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="设置角色" label-width="160">
          <template>
            <el-select v-model="addForm.roless" clearable value-key="id" placeholder="请选择">
              <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item">
              </el-option>
            </el-select>
          </template>

        </el-form-item>


        <el-form-item label="上传头像" label-width="160">
          <el-input v-model="addForm.headImage" autocomplete="off"></el-input>


          <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url" alt=""
              >
              <span class="el-upload-list__item-actions">
        <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleDownload(file)"
        >
          <i class="el-icon-download"></i>
        </span>
        <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
            </div>
          </el-upload>
          <el-dialog>
            <img width="100%" alt="">
          </el-dialog>

          <!--          上传-->
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reDate">取 消</el-button>
        <el-button type="primary" @click="addAndUpdate">确 定</el-button>
      </div>
    </el-dialog>


    <!--   设置角色弹框-->
    <el-dialog title="设置角色" :visible.sync="setRoleVisible" :close-on-click-modal="false">
      <el-form :model="roleMenu" label-width="80px" ref="saveForm">
        <!--indeterminate 属性用以表示 checkbox 的不确定状态，一般用于实现全选的效果 -->
        <template>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
          </el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="role_menu.menuIds" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="role in roleMenu2" :label="role.id" :key="role.id">{{ role.name }}</el-checkbox>
          </el-checkbox-group>
        </template>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="setRoleVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveRole" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>




export default {
  data() {
    return {
      img: '../../assets/bg1.jpg',


      isIndeterminate: false,
      listLoading: false,
      sels: [],//列表选中列

      editFormVisible: false,//编辑界面是否显示
      editLoading: false,

      addFormVisible: false,//新增界面是否显示
      addLoading: false,
      addFormRules: {
        username: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ]
      },
      //新增界面数据
      addForm: {
        id: null,
        username: '',
        age: 0,
        email: '',
        password: '',
        headImage: '',
        phone:'',
        department: {
          id: null,
          path: ''
        },
        roles: [{
          id: null,
          name: ''
        }],
        logininfoId:null

      },
      query: {
        pageSize: 10,
        currentPage: 1,
        keywords: ''
      },
      employeeInfo: {
        rows: [],

        total: 0,
      },
      dialogFormVisible: false,
      deptTree: [],
      options: [{
        id: null,
        name: ''
      }],

      setRoleVisible: false,
      roleMenu: {},
      //
      roleMenu2: [],
      checkAll: false,

      role_menu: {
        menuIds: [],
        roleId: null
      },
      rolesed: [],
      emps:[]

    }

  },
  methods: {


    //快速选择
    handleCheckAllChange(val) {

      let arry = []
      for (let i = 0; i < this.roleMenu2.length; i++) {

        arry.push(parseInt(this.roleMenu2[i].id))
      }
      this.role_menu.menuIds = val ? arry : []
    },

    //保存角色设置
    saveRole() {

      this.$http.post("/role/emp_role/update", this.role_menu)
          .then(result => {
            result = result.data;
            if (result.success) {
              this.$message({
                message: '保存成功' + result.message,
                type: 'success'
              });

            } else {
              this.$message({
                message: '保存失败' + result.message,
                type: 'error'
              });
            }
            this.setRoleVisible = false;
          })
          // .catch(result => {
          //
          // })


    },
    handleCheckedCitiesChange(val) {
      this.role_menu.menuIds = val
    },
    //显示设置角色页面
    handleRole(index, row) {
      this.setRoleVisible = true;
      this.getReturnRoleData(row.id)
      this.getRolesDates();
      this.role_menu.roleId = row.id


    },
    //回显角色数据
    getReturnRoleData(id) {
      this.$http.get("/role/emp_role/data/" + id)
          .then(result => {
            result = result.data;
            if (result.success) {
              var map = result.object.map(id => id);

              this.role_menu.menuIds = map

            } else {
              this.$message({
                message: '暂无权限',
                type: 'error'
              });
            }
          })

    },

    //获取角色数据
    getRolesDates() {
      this.$http.get("/role")
          .then(result => {

            result = result.data;
            if (result.success) {

              this.options = result.object
              this.roleMenu2 = result.object
            }
          })
    },

    //获取部门数据
    getDeptData() {
      this.$http.get("/department/tree")
          .then(result => {
            result = result.data;
            if (result.success) {
              this.deptTree = result.object
            }else {
              this.$message({
                message: '获取部门数据失败',
                type: 'error'
              });
            }
          })
          .catch(result=>{
            this.$message({
              message: '获取部门数据失败',
              type: 'error'
            });
          })
    },
    //性别显示转换
    formatSex: function (row, column) {
      return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
    },
    //模糊搜索
    keywordsSearch() {
      this.query.currentPage = 1;
      this.getEmployee();
    },
    handleCurrentChange(val) {
      this.query.currentPage = val;
      this.getEmployee();
    },
    handleSizeChange(val) {
      this.query.currentPage = 1;
      this.query.pageSize = val;

      this.getEmployee();
    },
    //获取用户列表
    getEmployee() {

      this.$http.put("/employee", this.query)
          .then(res => {
            res = res.data

            if (res.success) {

              this.employeeInfo = res.object;
            }
          })
          .catch(err => {
            this.$message({
              message: '分页查询失败' + err.message,
              type: 'error'
            });
          })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {

        //调用员工部门删除接口
        this.$http.delete("/employee/" + row.id)
            .then(result => {
              result = result.data;
              if (result.success) {
                this.$message({message: '删除成功', type: 'success'});
              } else {
                this.$message({message: '删除失败' + result.message, type: 'error'});
              }
              //刷新当前数据
              this.query.currentPage = 1;
              this.getEmployee();
            })
            .catch(result => {
              this.$message({message: '网络出错了', type: 'error'});
            })

      }).catch(() => {
        this.$message({message: '取消删除', type: 'info'});
      });
    },

    //取消，刷新页面
    reDate() {
      this.dialogFormVisible = false
      this.getEmployee()
    },

    //显示编辑界面
    handleEdit: function (index, row) {

      this.dialogFormVisible = true;

      var split = row.department.path.split("/");
      let arry = []
      for (let i = 1; i < split.length; i++) {
        arry.push(parseInt(split[i]))
      }
      row.department = arry;
      this.addForm = row
      //获取角色数据
      this.getRolesDates()
      this.getDeptData()
    },
    //显示新增界面
    handleAdd: function () {
      this.addForm = {
        id: null,
        username: '',
        age: 0,
        email: '',
        headImage: '',
        phone:'',
        department: {
          id: null,
          path: ''
        },
        logininfoId:null
      }

      this.dialogFormVisible = true;
      //获取角色数据
      this.getRolesDates()
      this.getDeptData()
    },

    //新增/修改
    addAndUpdate: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            //this.addLoading = true;
            var department = this.addForm.department;

            if (!department || department.length == 0) {
              this.addForm.department = {
                id: null
              }
            }
            if (department.length > 1) {
              for (let i = 1; i < department.length; i++) {
                this.addForm.department = {
                  id: department[i]
                }

              }
            } else {
              for (let i = 0; i < department.length; i++) {
                this.addForm.department = {
                  id: department[i]
                }

              }
            }

            // console.log( this.addForm);
            // return ;
            //调用后端增加或者删除接口
            this.$http.post("/employee", this.addForm)
                .then(result => {
                  result = result.data;
                  if (result.success) {
                    this.$message({type: 'success', message: result.message});

                  } else {
                    this.$message({type: 'error', message: result.message});
                  }
                  this.dialogFormVisible = false;

                  this.query.currentPage = 1;
                  this.getEmployee();
                })
                .catch(result => {
                  this.$message({type: 'error', message: "网络出错了"});
                })


          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchEmpDelete: function () {
      if (this.sels.length < 1) {
        this.$message({message: '你还没有选择删除的数据', type: 'info'});
        return;
      }

      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        //调用批量删除接口
        this.$http.patch("/employee", ids)
            .then(result => {
              result = result.data;
              if (result.success) {
                this.$message({message: '批量删除成功', type: 'success'});
              } else {
                this.$message({message: '删除失败' + result.message, type: 'error'});
              }

              //刷新当前数据
              this.query.currentPage = 1;
              this.getEmployee();
            })
            .catch(result => {
              this.$message({message: '网络出错了', type: 'error'});
            })
      }).catch(() => {
        this.$message({message: '取消删除', type: 'info'});
      });
    }
  },
  mounted() {
    this.getEmployee();
    this.getRolesDates();
  }
}

</script>

<style>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>